package net.receiving.converter;

import net.IncomingMessage;
import net.Client;
import net.DataBaseClient;
import net.message.*;

import java.util.Arrays;
import java.net.InetAddress;

import util.Config;

public class Converter {

    private static final byte SPECIAL = 0;

    private static IncomingMessage createIncomingMessage(byte[] data, int length, InetAddress ip, boolean flag) {
        int first = 0;
        while (data[first] != SPECIAL) {
            first++;
        }
        String clientName = createString(data, 0, first);
        if (flag) DataBaseClient.getInstance().add(clientName, ip);
        MessageType type = MessageType.values()[data[first + 1]];
        Message message = getMessage(type, data, first + 2);
        //if(flag)return new IncomingMessage(message, new Client(ip, clientName));
        return new IncomingMessage(message, new Client(DataBaseClient.getInstance().getAddress(clientName), clientName));
    }

    public static IncomingMessage createIncomingMessage(byte[] data, int length, InetAddress ip) {
        return createIncomingMessage(data, length, ip, true);
    }

    public static IncomingMessage createIncomingMessage(byte[] data, int length) {
        return createIncomingMessage(data, length, null, false);
    }

    private static String createString(byte[] a, int first, int last) {
        return new String(a, first, last);
    }

    private static Message getMessage(MessageType type, byte[] data, int offset) {
        return Generator.getInstance().getMessage(type, Arrays.copyOfRange(data, offset, data.length));
    }

    public static byte[] convertToByteArray(Message message) {
        byte[] clientName = Config.getInstance().getName().getBytes(Config.getInstance().getEncoding());
        byte messageName = (byte) message.getType().ordinal();
        byte[] messageInfo = message.toByteArray();

        byte[] data = new byte[clientName.length + 1 + 1 + messageInfo.length];
        System.arraycopy(clientName, 0, data, 0, clientName.length);
        data[clientName.length] = SPECIAL;
        data[clientName.length + 1] = messageName;
        System.arraycopy(messageInfo, 0, data, clientName.length + 2, messageInfo.length);
        return data;
    }


}
